package com.nativetalk.controller.app.three.teacher.reserve;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.reserve.TdNtReserveTimeDetail;
import com.nativetalk.bean.teacher.TdNtTeacherResult;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.JsonUtil;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.service.three.reserve.time.insert.ThreeReserveTimeInsertService;
import com.nativetalk.service.three.reserve.time.search.ThreeReserveTimeSearchService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by Peter on 2017-03-06
 */
@Controller
public class FourTeacherReserveController {
    private static Logger logger = Logger.getLogger(FourTeacherReserveController.class);
    @Resource
    private ThreeReserveTimeSearchService threeReserveTimeSearchService;
    @Resource
    private ThreeReserveTimeInsertService threeReserveTimeInsertService;

    /**
     * @return RetInfo
     * @Purpose 把某段时间设置为可预约或不可预约
     * @version 4.1
     * @time 2017-03-06
     * @author Peter
     */
    @RequestMapping(value = "/app/11/teatoken/teacher/reserve/time/update", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo set(@RequestBody TdNtReserveTimeDetail detail,
                       @RequestHeader(value = "token", required = false) String token) {

        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(detail));

            //校验token，如果校验通过就从缓存中读取Teacher
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = new RetInfo();
                retInfo.setMark("100");
                retInfo.setTip("Parameter token  is required");
                logger.info(retInfo.toString());
                return retInfo;
            }
            Object o = MemcachedUtils.get(token);
            if (o == null) {
                RetInfo retInfo = new RetInfo();
                retInfo.setMark("100");
                retInfo.setTip("Parameter token  is required");
                logger.info("缓存中没有teatoken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + retInfo);
                return retInfo;
            }

            if (!TdNtTeacherResult.class.isInstance(o)) {
                RetInfo retInfo = new RetInfo();
                retInfo.setMark("100");
                retInfo.setTip("Parameter token  is required");
                logger.info("缓存的token不是TdNtTeacherResult类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + retInfo);
                return retInfo;
            }
            TdNtTeacherResult tdNtTeacherResult = (TdNtTeacherResult) o;

            detail.setTea_id(tdNtTeacherResult.getTea_id());
    //      TimeZone tz = TimeZone.getTimeZone("America/New_York");
            String clientTimeZoneId = detail.getClientTimeZoneId();
    //      校验时区是否为空

            if (StringUtils.isEmpty(clientTimeZoneId)) {
                RetInfo retInfo = new RetInfo();
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("Invalid TimeZone");
                logger.error("时区id为空 clientTimeZoneId：" + clientTimeZoneId);
                return retInfo;
            }

            //校验时区是否有效
            TimeZone clientTimeZone = TimeZone.getTimeZone(clientTimeZoneId);
            if (clientTimeZone == null) {
                RetInfo retInfo = new RetInfo();
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("Invalid TimeZone");
                logger.error("时区无效clientTimeZoneId：" + clientTimeZoneId);
                return retInfo;
            }

            StringBuffer sb = new StringBuffer("\n--------------- param ------------");
            sb.append("\n " + detail + "\n --------------- param end/------------");
            logger.info(sb.toString());
            RetInfo retInfo = threeReserveTimeInsertService.updateTdNtReserveTimeSetIsValid(detail, clientTimeZone);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }

    }

    /**
     * @param token 用户标识,date：用户当地时区的时间戳，转换成date对象
     * @return RetInfo
     * @Purpose 根据当前日期（date参数）查询老师预约时间计划列表（数据库表：td_nt_reserve_time）
     * @version 4.1
     * @time 2017-03-06
     * @author Peter
     */
    @RequestMapping(value = "/app/11/teatoken/teacher/reserve/time/find", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo find(@RequestBody TdNtReserveTimeDetail detail,
                        @RequestHeader(value = "token", required = false) String token) {
        RetInfo retInfo = new RetInfo();
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(detail));

            TdNtTeacherResult tdNtTeacherResult = (TdNtTeacherResult) MemcachedUtils.get(token);
            String clientTimeZoneId = detail.getClientTimeZoneId();
            //校验时区是否为空
            if (StringUtils.isEmpty(clientTimeZoneId)) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("Invalid TimeZone");
                logger.error("时区id为空 clientTimeZoneId：" + clientTimeZoneId);
                return retInfo;
            }

            //校验时区是否有效
            TimeZone clientTimeZone = TimeZone.getTimeZone(clientTimeZoneId);
            if (clientTimeZone == null) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("Invalid TimeZone");
                logger.error("时区无效clientTimeZoneId：" + clientTimeZoneId);
                return retInfo;
            }
            StringBuffer sb = new StringBuffer("\n--------------- param ------------");
            sb.append("\n " + detail + "\n --------------- param end/------------");
            logger.info(sb.toString());
            retInfo = threeReserveTimeSearchService.findAllTeacherReserveTime(tdNtTeacherResult.getTea_id(), detail.getDate(), clientTimeZone);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }

    }

    public static void main(String[] args) {
        Date d = new Date();
        System.out.println(d.getTime());
    }

//    private Date changeToGmt8(Date date){
//        Calendar c =  Calendar.getInstance();
//
//    }

}



